<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <a-form :form="form" slot="detail">
        <a-row>
          <a-col :span="24">
            <a-form-item label="所属分类" :labelCol="labelCol" :wrapperCol="wrapperCol">
<!--              <a-input v-decorator="['goodsCategoryId', validatorRules.goodsCategoryId]" placeholder="请输入所属分类"></a-input>-->
              <j-tree-select
                ref="treeSelect"
                placeholder="请选择上级分类"
                v-decorator="['goodsCategoryId', validatorRules.pid]"
                dict="biz_goods_category,name,id"
                pidField="goodsCategoryId"
                pidValue="0"
                @change="treeChange"
                :disabled="isEditForm"
                hasChildField="has_child">
              </j-tree-select>
            </a-form-item>
          </a-col>
          <a-col :span="24" v-if="show_guige">
            <a-form-item label="规格" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-card>
                <a-row>
                  <a-col>
                    <div v-for="(i,index) in value" :key="index" style="margin-bottom: 30px">
                      <div :style="{ borderBottom: '1px solid #E9E9E9',paddingBottom:'10px', marginBottom:'10px'}">
                        <span>
                          {{i.attributeName}}
                        </span>
                      </div>
                      <a-checkbox-group v-model="linshiarr[index].checkedList" :options="linshiarr[index].plainOptions" @change="onChange(index)" />
                    </div>
                  </a-col>
                </a-row>
              </a-card>

              <a-card>
                <a-button type="primary" :disabled="isTongbuBtn" @click="setTableColumns">同步商品规格</a-button>
<!--                <a-button type="primary"  @click="setTableColumns">同步商品规格</a-button>-->
<!--                <a-button type="primary" :disabled="isTongbuBtn" @click="setTableDataSource">表格数据</a-button>-->
                <div style="margin-top: 20px" >
                  <a-table
                    ref="table"
                    size="small"
                    bordered
                    rowKey="id"
                    :columns="columns"
                    :dataSource="dataSource"
                    class="j-table-force-nowrap"
                  >
                    <template slot="imgSlot" slot-scope="text, record,index">
                      <j-image-upload  v-model="text" :isMultiple="formDisabled" @change="showPic(index,'image',$event)"></j-image-upload>
<!--                      <span  style="font-size: 12px;font-style: italic;">无图片</span>-->
<!--                      <img v-else :src="getImgView(text)" height="25px" alt="" style="max-width:80px;font-size: 12px;font-style: italic;"/>-->
                    </template>
                    <span slot="sortNum" slot-scope="text, record,index">
                      <editable-cell  :text="index+1" @change="onCellChange(index, 'sortNum', $event)"  />
                    </span>

                    <span slot="action" slot-scope="text, record,index">
                      <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(text, record,index)">
                        <a>删除</a>
                      </a-popconfirm>
                    </span>
                  </a-table>
                </div>
              </a-card>




            </a-form-item>
          </a-col>
          <a-col :span="24" v-if="isEditForm">
            <!--编辑状态用-->
            <a-form-item label="规格" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <a-card>
              <div style="margin-top: 20px" >
                <a-table
                  ref="table"
                  size="small"
                  bordered
                  rowKey="id"
                  :columns="columns"
                  :dataSource="dataSource"
                  class="j-table-force-nowrap"
                >
                  <template slot="imgSlot" slot-scope="text, record,index">
                    <j-image-upload v-if="text" v-model="text" :isMultiple="formDisabled" @change="showPicEdit(index,'image',record, $event)" style="position: absolute;height: 45px;width: 45px;opacity: 0"></j-image-upload>
<!--                    <span v-else style="font-size: 12px;font-style: italic;">无图片</span>-->
                    <img :src="getImgView(text)" height="45px" alt="" style="max-width:80px;font-size: 12px;font-style: italic;"/>
                  </template>
                  <span slot="sortNum" slot-scope="text, record,index">
                      <editable-cell  :text="index+1" @change="onCellChange(index, 'sortNum', $event)"  />
                    </span>

                  <span slot="action" slot-scope="text, record,index">
                      <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(text, record,index)">
                        <a>删除</a>
                      </a-popconfirm>
                    </span>
                </a-table>
              </div>
            </a-card>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['name', validatorRules.name]" placeholder="请输入名称"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="简介" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-textarea v-decorator="['synopsis', validatorRules.synopsis]" rows="4" placeholder="请输入简介"/>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="商品图" :labelCol="{span:10}" :wrapperCol="{span:12}">
              <j-image-upload :isMultiple="formDisabled" v-decorator="['pic', validatorRules.pic]"></j-image-upload>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="团购图" :labelCol="{span:4}" :wrapperCol="{span:20}">
              <j-image-upload :isMultiple="formDisabled" v-decorator="['groupPurchasePic', validatorRules.groupPurchasePic]"></j-image-upload>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="轮播图" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-image-upload isMultiple v-decorator="['albumPics', validatorRules.albumPics]"></j-image-upload>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="视频" :labelCol="{span:10}" :wrapperCol="{span:12}">
              <j-video-upload :isMultiple="formDisabled" v-decorator="['videoUrl', validatorRules.videoUrl]"></j-video-upload>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="视频封面" :labelCol="{span:4}" :wrapperCol="{span:20}">
              <j-image-upload :isMultiple="formDisabled" v-decorator="['videoCover', validatorRules.videoCover]"></j-image-upload>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="排序" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input-number v-decorator="['sort', validatorRules.sort]" :min="1" placeholder="请输入排序" style="width: 100%"/>
            </a-form-item>
          </a-col>
          <a-col :span="24" v-if="title == '编辑'">
            <a-form-item label="库存单位" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input disabled v-decorator="['unitName']" :min="1"   style="width: 100%"/>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="商品详情" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-editor v-decorator="['detail',{trigger:'input'}, validatorRules.detail]"/>
            </a-form-item>
          </a-col>
          <a-col v-if="showFlowSubmitButton" :span="24" style="text-align: center">
            <a-button @click="submitForm">提 交</a-button>
          </a-col>
        </a-row>
      </a-form>
<!--      <span v-text="showTXT"></span>-->
    </j-form-container>
  </a-spin>
</template>

<script>

  import { httpAction, getAction } from '@/api/manage'
  import pick from 'lodash.pick'
  import { validateDuplicateValue } from '@/utils/util'
  import JFormContainer from '@/components/jeecg/JFormContainer'
  import JImageUpload from '@/components/jeecg/JImageUpload'
  import JVideoUpload from '@/components/jeecg/JVideoUpload'
  import JEditor from '@/components/jeecg/JEditor'
  import JTreeSelect from '@/components/jeecg/JTreeSelect1'
  import { putAction } from '../../../api/manage'
  import JDictSelectTag from "@/components/dict/JDictSelectTag"
  import EditableCell from './Edittablecell'
  import { mixinDevice } from '@/utils/mixin'
  import { JeecgListMixin } from '@/mixins/JeecgListMixin1'


  export default {
    name: 'GoodsForm',
    mixins:[JeecgListMixin, mixinDevice],
    components: {
      JFormContainer,
      JImageUpload,
      JDictSelectTag,
      JVideoUpload,
      JEditor,
      JTreeSelect,
      EditableCell,
    },
    props: {
      //流程表单data
      formData: {
        type: Object,
        default: ()=>{},
        required: false
      },
      //表单模式：true流程表单 false普通表单
      formBpm: {
        type: Boolean,
        default: false,
        required: false
      },
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      },
      title:{
        type: String,
        default: null,

      }
    },
    data () {
      return {
        shipinUrl:'',
        showTXT:'',
        linshiarrNew:[],
        //是否是编辑状态
        isEditForm:false,
        //规格提交数据
        goodsSpecsList:[],
        //规格表数据
        dataSource:[],
        //规格表头
        columns:[],
        //同步商品规格列表按钮状态
        isTongbuBtn:true,
        checkedList: [],
        indeterminate: false,
        checkAll: false,
        plainOptions:['Apple', 'Pear', 'Orange'],
        value: [],
        show_guige:false,
        form: this.$form.createForm(this),
        model: {},
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        confirmLoading: false,
        validatorRules: {

          albumPics:{
            rules: [
              { required: true, message: '请选择轮播图!'},
            ]
          },
          detail: {
            rules: [
              { required: true, message: '请填写商品详情!'},
            ]
          },
          pic: {
            rules: [
              { required: true, message: '请上传商品图!'},
            ]
          },
          pid: {
            rules: [
              { required: true, message: '请选择分类!'},
            ]
          },
          synopsis: {
            rules: [
              { required: true, message: '请输入简介!'},
            ]
          },
          goodsCategoryId: {
            rules: [
              { required: true, message: '请输入所属分类!'},
            ]
          },
          name: {
            rules: [
              { required: true, message: '请输入名称!'},
            ]
          },
          sort: {
            rules: [
              { required: false},
              { pattern: /^-?\d+$/, message: '请输入整数!'},
            ]
          },
          videoUrl:{
            rules: [
              { required: false, message: '请选择视频!'},
              /*{
                validator: (rule, value, callback) => {
                  this.shipinUrl = value
                },
              },*/
            ]
          },
          videoCover: {
            rules: [
              { required: false, message: '请选择视频封面!'},
              /*{
                validator: (rule, value, callback) => {
                  console.log('value',value)
                  if (this.shipinUrl!=='' && value==undefined){
                    callback(new Error("请选择视频封面!"));
                  }else {
                    callback()
                  }
                },
              },*/
            ]
          },
        },
        url: {
          add: "/goods/add",
          edit: "/goods/edit",
          queryById: "/goods/queryById",
          getByCategoryId:"/specsattribute/bizSpecsAttribute/getByCategoryId"
        },
        linshiarr:[
          {
            indeterminate: false,
            plainOptions:['Apple', 'Pear', 'Orange'],
            checkAll: false,
            checkedList: [],
          }
        ],
      }
    },
    computed: {
      formDisabled(){
        if(this.formBpm===true){
          if(this.formData.disabled===false){
            return false
          }
          return true
        }
        return this.disabled
      },
      showFlowSubmitButton(){
        if(this.formBpm===true){
          if(this.formData.disabled===false){
            return true
          }
        }
        return false
      }
    },
    created () {
      //如果是流程中表单，则需要加载流程表单data
      this.showFlowData();
    },
    mounted() {


    },
    watch:{

      //监听规格被选中后
      linshiarr:{
        handler(newVal) {
          /*旧版本====没中规格都选中才激活按钮*/
          /*for (let nElement of newVal) {
            if (nElement.checkedList.length==0){
              this.isTongbuBtn = true
              return false
            }
          }
          this.isTongbuBtn = false
          */
          /*新版本====规格选中1种就可以激活按钮*/
          for (let nElement of newVal) {
            if (nElement.checkedList.length!==0){
              this.isTongbuBtn = false
              return false
            }
          }
          this.isTongbuBtn = true
        },
        deep: true,
        immediate: false,
      }
    },
    methods: {
      //查看 保存 规格照片地址
      showPic(key, dataIndex, value){
        console.log(key, dataIndex, value)
        const dataSource = [...this.dataSource];
        dataSource[key][dataIndex] = value;
        this.dataSource = dataSource;
      },
      //编辑时候的照片地址
      showPicEdit(key, dataIndex, record,value){
        console.log(key, dataIndex,record, value)
        console.log('aaaa',this.dataSource)
        // const dataSource = [...this.dataSource];
        this.dataSource[key][dataIndex] = value;
        console.log('bbbb',this.dataSource)
        // this.dataSource = dataSource;
      },
      onCellChange(key, dataIndex, value) {
        const dataSource = [...this.dataSource];
        // const target = dataSource.find(item => item.key === key);

          dataSource[key][dataIndex] = value;
          this.dataSource = dataSource;

      },
      //删除规格表中某行
      handleDelete(text,record,index){
        console.log('this.linshiarr',this.linshiarr)
        console.log(this.dataSource)
        this.dataSource.splice(index,1)
      },
      //动态设置key
      /*dongtaiKey(key, value){
        let obj = {};
        obj[key] = value;
        return obj;
      },*/
      //生成table多维数据
      setTableDataSource(arr0){
        // let key1 = this.dongtaiKey(this.linshiarr[0].attributeName,this.linshiarr[0].checkedList[0])
        // console.log(key1)
        let array4 = []
        for (let array4Element of arr0) {
          array4.push(array4Element.checkedList)
        }
        var result = array4.reduce((last, current) => {
          const array = [];
          last.forEach((par1,index1) => {
            current.forEach((par2,index2) => {
              array.push(par1 + "," + par2 );
            });
          });
          return array;
        });
        // console.log(result)
        let arr = []
        for (let argument of result) {
          arr.push(argument.split(','))
        }
        // console.log(arr)

        //合并规格方法
        function name(arr1, arr2) {
          let arr1key = []
          arr1.forEach(item => {
            let val = item['attributeName']
            arr1key.push(val)
          });

          let arrAll = []
          arr2.forEach(item => {   // ['10斤', '大包', '试用装2']
            let objAll = {}
            for (var i = 0; i < arr1key.length; i++) {
              let obj = {};
              for (var j = 0; j < item.length; j++) {
                if (i == j) {
                  obj[arr1key[i]]=item[j]
                  Object.assign(objAll,obj)
                }
              }
            }
            arrAll.push(objAll)
          })
          return arrAll
        }
        // console.log(arrFinal)
        this.dataSource = name(this.linshiarr,arr)

        //初始化dataSource的排序和图片字段
        let ii = 1
        for (let array4Element of this.dataSource) {
          array4Element.sortNum = ii++
          array4Element.image = ''
        }
      },
      //生成表格列头===同步商品规格
      setTableColumns(){
        let filterArr = this.linshiarr.filter((item)=>{
          if (item.checkedList.length>0){
            return item
          }
        })
        console.log('filterArr',filterArr)
        // this.linshiarrNew = filterArr
        // this.linshiarr = filterArr
        // debugger
        /*let arrr = this.linshiarr
        let arrNull = []
        for (let arrrElement of arrr) {
          if (arrrElement.checkAll){
            arrNull.push(arrrElement)
          }
        }
console.log(arrNull)*/

        console.log('this.linshiarr',this.linshiarr)
        this.columns = []
        for (let key of filterArr) {
          let tempArr = Object.keys(key)
          let obj = {
            title:key.attributeName,
            align:"center",
            dataIndex:key.attributeName
          }
          this.columns.push(obj)
        }
        let imgSlot = {
          title: '图片',
          dataIndex: 'image',
          align:"center",
          width:'20%',
          scopedSlots: { customRender: 'imgSlot' }
        }
        let sortNum = {
          title: '排序',
          dataIndex: 'sortNum',
          align:"center",
          width:'20%',
          scopedSlots: { customRender: 'sortNum' },
        }
        let caozuo = {
          title: '操作',
          dataIndex: 'action',
          align:"center",
          scopedSlots: { customRender: 'action' }
        }
        let indexrow = {
          title: '序号',
          dataIndex: '',
          key:'rowIndex',
          width:60,
          align:"center",
          customRender:function (t,r,index) {
          return parseInt(index)+1;
        },
        }
        this.columns.push(imgSlot)
        this.columns.push(sortNum)
        this.columns.push(caozuo)
        this.columns.unshift(indexrow)
        // console.log(this.columns)
        this.setTableDataSource(filterArr)
      },


      //生成编辑状态下的表格列头和表格数据
      setTableColumnsEdit(res){
        console.log(res)
        this.columns = []
        for (let key of res[0].specsValues) {
          if (key.attributeName !=='sortNum' && key.attributeName !=='image'){
            let obj = {
              title:key.attributeName,
              align:"center",
              dataIndex:key.attributeName
            }
            this.columns.push(obj)
          }


        }
        let imgSlot = {
          title: '图片',
          dataIndex: 'image',
          align:"center",
          width:'10%',
          scopedSlots: { customRender: 'imgSlot' }
        }
        let price = {
          title: '价格',
          dataIndex: 'price',
          align:"center",
        }
        let stock = {
          title: '库存',
          dataIndex: 'stock',
          align:"center",
        }
        let sortNum = {
          title: '排序',
          dataIndex: 'sortNum',
          align:"center",
          width:'20%',
          scopedSlots: { customRender: 'sortNum' },
        }

        let indexrow = {
          title: '序号',
          dataIndex: '',
          key:'rowIndex',
          width:60,
          align:"center",
          customRender:function (t,r,index) {
            return parseInt(index)+1;
          },
        }

        this.columns.push(price)
        this.columns.push(stock)
        this.columns.push(imgSlot)
        this.columns.push(sortNum)
        this.columns.unshift(indexrow)


        // console.log(this.columns)
        // this.setTableDataSource()
        /*生成编辑状态DataSource*/
        this.dataSource = []
        for (let ele of res) {
          let obj = {}
          for (let eleElement of ele.specsValues) {

            obj[eleElement.attributeName] = eleElement.attributeValues
            // console.log(obj)
          }
          obj.stock = ele.stock
          obj.price = ele.price
          this.dataSource.push(obj)
        }
        console.log(this.dataSource)
      },



      //选择规格
      onChange(index) {
        this.linshiarr[index].indeterminate = !!this.linshiarr[index].checkedList.length && this.linshiarr[index].checkedList.length < this.linshiarr[index].plainOptions.length;
        this.linshiarr[index].checkAll = this.linshiarr[index].length === this.linshiarr[index].plainOptions.length;
        // console.log('this.linshiarr[index].checkedList',this.linshiarr[index].checkedList)
        console.log('this.linshiarr',this.linshiarr)
      },

      //分类下拉改变
      treeChange(e){
        this.show_guige = false
        this.linshiarr = []  //重置缓存数组
        this.dataSource = []  //重置表格数据
        this.columns = []   //重置表头设置
        // console.log(e)
        let params = {categoryId:e};
        getAction(this.url.getByCategoryId,params).then((res)=>{
          if (res.success){
            this.show_guige = true
            this.value = res.result
            console.log('res.result',res.result)
            for (let eElement of this.value) {
              let obj = {}
              obj.attributeName = eElement.attributeName
              obj.indeterminate= false
              obj.checkAll=false
              obj.plainOptions = []
              obj.checkedList= []
              for (let eElement1 of eElement.bizSpecsAttributeValuesList) {
                obj.plainOptions.push(eElement1.attributeValues)
              }
              this.linshiarr.push(obj)

            }
          console.log('this.linshiarr',this.linshiarr)
          }else {
            this.$message.error('该分类暂未设定规格属性')
            this.show_guige = false
            return false
          }

        })
      },
      add () {
        this.edit({});
      },
      edit (record) {
        this.form.resetFields();
        this.model = Object.assign({}, record);
        this.visible = true;
        this.$nextTick(() => {
          this.form.setFieldsValue(pick(this.model,'goodsCategoryId','videoCover','name','unitName','synopsis','pic','groupPurchasePic','albumPics','videoUrl','sort','detail'))
        })
      },
      //渲染流程表单数据
      showFlowData(){
        if(this.formBpm === true){
          let params = {id:this.formData.dataId};
          getAction(this.url.queryById,params).then((res)=>{
            if(res.success){
              this.edit (res.result);
            }
          });
        }
      },
      submitForm () {
        const that = this;
        // 触发表单验证
        this.form.validateFields((err, values) => {


          console.log('values',values)
          if (values.videoUrl && values.videoCover==undefined){
            this.$message.error('请选择上传视频封面')
            return false
          }
          if (!err) {
            that.confirmLoading = true;
            let httpurl = '';
            let method = '';
            if(!this.model.id){
              httpurl+=this.url.add;
              method = 'post';
            }else{
              httpurl+=this.url.edit;
               method = 'put';
            }
            /*let obj = [
              {

                attributeName:'重量',
                bizSpecsAttributeValuesList:['10斤','30斤']
              },
              {
                attributeName:'包装',
                bizSpecsAttributeValuesList:['中杯','小杯']
              }
            ]*/


            /*转化规格列表*/
            let goodsSpecsList = []
            for (let ele of this.dataSource) {
              console.log(ele)
              let obj1 = {}
              let arr1 = []
              for (let ele2 in ele) {
                let obj2 = {}
                obj2.attributeName = ele2
                obj2.attributeValues = ele[ele2]
                arr1.push(obj2)
              }
              obj1.specsValues = arr1
              goodsSpecsList.push(obj1)
            }
            console.log('goodsSpecsList',goodsSpecsList)
            // debugger
            if (goodsSpecsList.length==0){
              this.$message.error('请选择规格并同步商品规格！')
              that.confirmLoading = false;
              return false
            }
            let formData = Object.assign(this.model, values,{goodsSpecsList:goodsSpecsList});
            // this.showTXT = formData
            console.log("表单提交数据",formData)
            httpAction(httpurl,formData,method).then((res)=>{
              if(res.success){
                that.$message.success(res.message);
                that.$emit('ok');
              }else{
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
            })
          }

        })
      },
      popupCallback(row){
        this.form.setFieldsValue(pick(row,'goodsCategoryId','name','videoCover','unitName','synopsis','pic','groupPurchasePic','albumPics','videoUrl','sort','detail'))
      },
    }
  }
</script>
<style scoped>
  .ant-table-row-cell-break-word{
    height: 100% !important;
  }
</style>